package com.ryskoo.permission.vendormanager.repository;

import com.ryskoo.common.constant.CacheConstant;
import com.ryskoo.framework.core.repository.BasicRedisImpl;
import com.ryskoo.framework.core.utils.RedisUtil;
import com.ryskoo.permission.vendormanager.domain.StoreManagerPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

@Primary
@Repository
public class VendorManagerRedisImpl extends BasicRedisImpl<StoreManagerPO> implements IVendorManagerRepository {
	@Autowired
	private RedisUtil redisClient;

	@Autowired
	private IVendorManagerRepository managerRepository;

	@PostConstruct
	public void init() {
		this.setRedisClient(redisClient);
		this.setDao(managerRepository);
	}
	
	public VendorManagerRedisImpl() {
		super(CacheConstant.PMS_MANAGER_KEY);
	}

    /**
     * 根据用户名查询管理员信息
     *
     * @param userName
     * @return
     */
    @Override
    public StoreManagerPO getManagerByLoginName(String userName) {
        //通过用户名先从缓存获取
        Object object = redisClient.getObject(CacheConstant.PMS_MANAGER_KEY + userName, StoreManagerPO.class);
        if (object != null) {
            return (StoreManagerPO) object;
        }
        //根据用户名查询管理员uuid
        String uuid = managerRepository.getManagerUuidByLoginName(userName);
        if (!StringUtils.isEmpty(uuid)) {
            StoreManagerPO manager = super.getByUuid(uuid);
            if (manager != null) {
                redisClient.setObject(CacheConstant.PMS_MANAGER_KEY + userName, manager);
                return manager;
            }
        }
        return null;
     }
    
	/**
	 * 根据用户名查询管理员uuid
	 *
	 * @param userName
	 * @return
	 */
	@Override
	public String getManagerUuidByLoginName(String userName) {
		return managerRepository.getManagerUuidByLoginName(userName);
	}
}
